package com.t3rik.mobile.mes.controller

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.t3rik.common.annotation.Log
import com.t3rik.common.annotation.RepeatSubmit
import com.t3rik.common.constant.UserConstants
import com.t3rik.common.core.controller.BaseController
import com.t3rik.common.core.domain.AjaxResult
import com.t3rik.common.core.page.TableDataInfo
import com.t3rik.common.enums.BusinessType
import com.t3rik.common.utils.StringUtils
import com.t3rik.mes.pro.domain.ProTask
import com.t3rik.mes.pro.service.IProTaskService
import com.t3rik.mobile.mes.dto.TaskClaimRequestDTO
import com.t3rik.mobile.mes.service.ITaskClaimService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import jakarta.annotation.Resource
import jakarta.validation.Valid
import org.springframework.web.bind.annotation.*

/**
 * 任务认领控制器
 * @author t3rik
 * @date 2024/12/18
 */
@Api(tags = ["任务认领管理"])
@RestController
@RequestMapping(UserConstants.MOBILE_PATH + "/task/claim")
class TaskClaimController : BaseController() {

    @Resource
    lateinit var taskClaimService: ITaskClaimService
    
    @Resource
    lateinit var proTaskService: IProTaskService

    /**
     * 查询可认领的任务列表（分页）
     */
    @ApiOperation("查询可认领的任务列表")
    @GetMapping("/available")
    fun getAvailableTasks(proTask: ProTask): TableDataInfo {
        // 获取查询条件
        val queryWrapper = getAvailableTasksQueryWrapper(proTask)
        // 组装分页
        val page = getMPPage<ProTask>(proTask)
        // 查询可认领的任务
        taskClaimService.listAvailableTasks(queryWrapper, page)
        return getDataTableWithPage(page)
    }
    
    /**
     * 获取任务详细信息
     */
    @ApiOperation("获取任务详细信息")
    @GetMapping("/{taskId}")
    fun getTaskInfo(@PathVariable("taskId") taskId: Long): AjaxResult {
        return AjaxResult.success(proTaskService.getById(taskId))
    }

    /**
     * 员工自主认领任务
     */
    @ApiOperation("员工自主认领任务")
    @Log(title = "任务认领", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PostMapping("/claim")
    fun claimTasks(@Valid @RequestBody claimRequest: TaskClaimRequestDTO): AjaxResult {
        val result = taskClaimService.claimTasks(claimRequest)
        return AjaxResult.success(result)
    }
    
    /**
     * 员工取消认领任务
     */
    @ApiOperation("员工取消认领任务")
    @Log(title = "取消任务认领", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PostMapping("/cancel")
    fun cancelClaimTasks(@Valid @RequestBody claimRequest: TaskClaimRequestDTO): AjaxResult {
        val result = taskClaimService.cancelClaimTasks(claimRequest)
        return AjaxResult.success(result)
    }
    
    /**
     * 获取可认领任务的查询条件
     */
    private fun getAvailableTasksQueryWrapper(proTask: ProTask): LambdaQueryWrapper<ProTask> {
        val queryWrapper = LambdaQueryWrapper<ProTask>()
        // 基本查询条件
        queryWrapper.eq(proTask.taskCode != null, ProTask::getTaskCode, proTask.taskCode)
        queryWrapper.like(StringUtils.isNotEmpty(proTask.taskName), ProTask::getTaskName, proTask.taskName)
        queryWrapper.like(StringUtils.isNotEmpty(proTask.workorderCode), ProTask::getWorkorderCode, proTask.workorderCode)
        queryWrapper.like(StringUtils.isNotEmpty(proTask.workorderName), ProTask::getWorkorderName, proTask.workorderName)
        queryWrapper.like(StringUtils.isNotEmpty(proTask.processName), ProTask::getProcessName, proTask.processName)
        
        // 时间范围查询
        val params = proTask.params
        if (params != null) {
            queryWrapper.between(
                params["beginTime"] != null && params["endTime"] != null,
                ProTask::getCreateTime, 
                params["beginTime"], 
                params["endTime"]
            )
        }
        
        // 可认领任务的特定条件：状态为PREPARE且未分配人员
        queryWrapper.eq(ProTask::getStatus, "PREPARE")
        queryWrapper.isNull(ProTask::getTaskUserId)
        
        queryWrapper.groupBy(ProTask::getTaskId)
        return queryWrapper
    }
}